package com.weixing.mall.provider.support.excel;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.collect.Lists;
import com.weixing.mall.base.exception.BusinessException;
import com.weixing.mall.core.support.auth.AuthUtil;
import com.weixing.mall.core.support.auth.SysAuth;
import com.weixing.mall.provider.api.model.vo.AgentVo;
import com.weixing.mall.provider.model.domain.AgentAccount;
import com.weixing.mall.provider.model.domain.AgentAccountBill;
import com.weixing.mall.provider.model.domain.AgentWithdraw;
import com.weixing.mall.provider.model.enums.*;
import com.weixing.mall.provider.service.IAgentAccountService;
import com.weixing.mall.provider.service.IAgentService;
import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 活动商品导入模版读取类
 *
 * @author Small
 */
public class AgentWithdrawImportDataListener extends AnalysisEventListener<AgentWithdrawExcelDownData> {
    private static final Logger LOGGER = LoggerFactory.getLogger(AgentWithdrawImportDataListener.class);
    private IAgentAccountService agentAccountService;
    private IAgentService agentService;
    List<AgentWithdrawExcelDownData> list = new ArrayList<AgentWithdrawExcelDownData>();

    public AgentWithdrawImportDataListener() {
    }
    public AgentWithdrawImportDataListener(IAgentAccountService agentAccountService,IAgentService agentService) {
        this.agentAccountService = agentAccountService;
        this.agentService = agentService;
    }
    @SneakyThrows
    @Override
    public void invoke(AgentWithdrawExcelDownData data, AnalysisContext context) {
        LOGGER.info("解析到一条数据:{}", JSON.toJSONString(data));
        list.add(data);
    }

    @SneakyThrows
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        saveData();
        LOGGER.info("所有数据解析完成！");
    }

    /**
     * 加上存储数据库
     */
    private void saveData() throws Exception {
        LOGGER.info("{}条数据，开始存储数据库！", list.size());
        SysAuth auth = AuthUtil.getSysExt();
        //封装待更新的数据
        List<AgentAccount> agentAccounts = Lists.newArrayList();
        //封装账户流水记录
        List<AgentAccountBill> agentAccountBills = Lists.newArrayList();
        //封装提现记录
        List<AgentWithdraw> agentWithdraws = Lists.newArrayList();

        list.forEach(awedd->{
            AgentVo agentVo =agentService.selectByAgentSn(awedd.getAgentSn());
            if(ObjectUtil.isNotEmpty(agentVo)&&agentVo.getId() != null){
                AgentAccount agentAccount = agentAccountService.getOne(new LambdaQueryWrapper<AgentAccount>()
                        .eq(AgentAccount::getAgentId,agentVo.getId()));
                if(ObjectUtil.isNotEmpty(agentAccount)
                        && awedd.getAmount() != null
                        && agentAccount.getAvaAmount().compareTo(awedd.getAmount()) > -1){
                    agentAccount.setAvaAmount(agentAccount.getAvaAmount().subtract(awedd.getAmount()));
                    //账户
                    agentAccounts.add(agentAccount);
                    //提现记录
                    agentWithdraws.add(createAgentWithdraw(agentVo,awedd,auth.getUid()));
                    //提现账户流水记录
                    agentAccountBills.add(createAgentAccountBill(agentVo,awedd,auth.getUid()));
                }else{
                    throw new BusinessException("优惠码："+awedd.getAgentSn()+"代理商可提现金额不足");
                }
            }else{
                throw new BusinessException("优惠码："+awedd.getAgentSn()+"代理商信息不存在");
            }
        });
        if(list.size() != agentAccounts.size()){
            throw new BusinessException("导入数据与数据库实际数据不一致");
        }
        agentAccountService.updateAvaAmountByAgentId(agentAccounts,agentAccountBills,agentWithdraws);
        LOGGER.info("存储数据库成功！");
    }

    private AgentWithdraw createAgentWithdraw(AgentVo agentVo,AgentWithdrawExcelDownData awedd,Long operatorId){
        AgentWithdraw aw = new AgentWithdraw();
        aw.setAgentId(agentVo.getId());
        aw.setAmount(awedd.getAmount());
        aw.setAuditResult(AgentWithdrawAuditEnum.ADOPT.getValue());
        aw.setAuditTime(new Date());
        aw.setAuditRemark("导入提现结算");
        aw.setOperator(operatorId);
        aw.setPayStatus(IsPayEnum.STATUS1.getValue());
        aw.setPayer(operatorId);
        aw.setPayType(AgentPayTypeEnum.TYPE1.getValue());
        aw.setPayAmount(awedd.getAmount());
        aw.setRemarks("系统提现结算");
        aw.setUpdatedBy(operatorId);
        aw.setCreatedTime(new Date());
        return aw;
    }

    private AgentAccountBill createAgentAccountBill(AgentVo agentVo,AgentWithdrawExcelDownData awedd,Long operatorId){
        //提现记录
        AgentAccountBill aab = new AgentAccountBill();
        aab.setAgentId(agentVo.getId());
        aab.setAmount(awedd.getAmount());
        aab.setTransType(BillTransTypeEnum.WITHDRAWAL.getValue());
        aab.setBillType(BillTypeEnum.OUTCOME.getValue());
        aab.setRelationId(operatorId);
        aab.setRemark("提现扣除");
        return aab;
    }
}
